package top.frsf.rpc.factory;

import top.frsf.rpc.enums.LoadBalanceEnum;
import top.frsf.rpc.loadbalance.LoadBalance;
import top.frsf.rpc.loadbalance.impl.RoundRobinLoadBalance;

import java.util.HashMap;
import java.util.Map;

/**
 * 负载均衡工厂类
 *
 * @author He Kuntao
 * @since 2025/7/18 11:13
 */
public class LoadBalanceFactory {

    /**
     * 负载均衡算法映射表
     */
    private static final Map<LoadBalanceEnum, LoadBalance> LOAD_BALANCE_MAP = new HashMap<>();

    static {
        // 添加负载均衡算法
        LOAD_BALANCE_MAP.put(LoadBalanceEnum.ROUND_ROBIN, new RoundRobinLoadBalance());
        LOAD_BALANCE_MAP.put(LoadBalanceEnum.RANDOM, new RoundRobinLoadBalance());
    }

    /**
     * 根据负载均衡策略获取负载均衡算法实例
     *
     * @param strategy 负载均衡策略
     * @return 负载均衡算法实例
     */
    public static LoadBalance getLoadBalance(LoadBalanceEnum strategy) {
        LoadBalance loadBalance = LOAD_BALANCE_MAP.get(strategy);
        if (loadBalance == null) {
            throw new IllegalArgumentException("Unsupported load balance strategy: " + strategy);
        }
        return loadBalance;
    }


    /**
     * 注册负载均衡算法
     *
     * @param strategy    负载均衡策略
     * @param loadBalance 负载均衡算法实例
     */
    public static void register(LoadBalanceEnum strategy, LoadBalance loadBalance) {
        LOAD_BALANCE_MAP.put(strategy, loadBalance);
    }
}
